package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: 祺诺
 * @Name; xqf
 * @Date: 2020/12/26 20:38
 */
@WebFilter("/*")
public  class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //获取域对象来判断是否登录
        //自带的 请求和响应需要转换成 http
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //因为登录有关的页面和servlet是不需要进入这个判断的
        String uri = req.getRequestURI();
        if((uri.endsWith("login.jsp"))||(uri.endsWith("LoginStudentServlet"))){
            //直接返回
            //直接放行
            filterChain.doFilter(req,resp);
            return;
        }
        //登陆成功是将user对象放入服务器域对象中
        Object user = req.getSession().getAttribute("user");
        if(user==null){
            //没登录信息直接转到登录页面
          resp.sendRedirect(req.getContextPath()+"/login.jsp");
        }else {
            filterChain.doFilter(req, resp);
        }
    }
}
